// 验证访问令牌
const jwt = require("jsonwebtoken");
const User = require("../models/User");

// 解析 Authorization: Bearer <token>
function auth(required = true) {
    return async (req, res, next) => {
        try {
            const header = req.headers.authorization || "";
            const [, token] = header.split(" ");
            if (!token) {
                if (!required) return next(); // 允许匿名访问
                return res.status(401).json({ message: "未认证" });
            }
            const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET);
            const user = await User.findById(payload.sub);
            if (!user) return res.status(401).json({ message: "无效用户" });
            req.user = user;
            next();
        } catch (err) {
            return res.status(401).json({ message: "访问令牌无效或已过期" });
        }
    };
}

// 权限：仅作者或管理员
function canModifyPost(getAuthorId) {
    return (req, res, next) => {
        const isAdmin = req.user?.role === "admin";
        const isOwner = String(getAuthorId(req)) === String(req.user?._id);
        if (isAdmin || isOwner) return next();
        return res.status(403).json({ message: "无权限执行此操作" });
    };
}

module.exports = { auth, canModifyPost };
